﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace IllustratedCsharp7_ch21_return_TaskValue
{
    class Chapt21_3_AsyncMethod_Ex4_Return_ValueTask_int
    {
        static void _Main()
        {
            ValueTask<int> value = value = DoAsyncStuff.CalculateSumAsync(0, 6);
            //处理其他事情            
            Console.WriteLine($"Value:{value.Result}");

            value = DoAsyncStuff.CalculateSumAsync(5,6);
            //处理其他事情
            Console.WriteLine($"Value:{value.Result}");         
        }
    }

    static class DoAsyncStuff
    {
        //使用返回ValueTask<int>对象的异步方法
        public static async ValueTask<int> CalculateSumAsync(int i1, int i2)
        {
            if (i1 == 0) //如果i1 == 0,则可以避免执行长时间的任务
            {
                return i2;
            }
            int sum = await Task.Run(() => GetSum(i1, i2));            
            return sum;        
        }
        private static int GetSum(int i1, int i2) { return i1 + i2; }
    }
}
